const fs = require('fs')
const path = require('path')

const envFileReader = file => {
  try {
    const fileName = path.join(__dirname, './', file)

    const data = fs
      .readFileSync(fileName, { encoding: 'utf8' })
      .split(/[\r\n]/)
      .filter(Boolean)

    return data
      .map(item => item.split('='))
      .reduce(
        (accumulator, current) => ({
          ...accumulator,
          [current[0].trim()]: current[1].trim()
        }),
        {}
      )
  } catch (error) {
    return {}
  }
}

const defineEnv = (mode, debugMode) => {
  const envs = {
    development: {
      enable: mode === 'development',
      env: {
        BABEL_ENV: 'development',
        NODE_ENV: 'development',
        EXT_APP_ENV: 'development'
      }
    },
    staging: {
      enable: mode === 'production' && debugMode === 'true',
      env: {
        BABEL_ENV: 'production',
        NODE_ENV: 'production',
        EXT_APP_ENV: 'staging'
      }
    },
    production: {
      enable: mode === 'production' && debugMode !== 'true',
      env: {
        BABEL_ENV: 'production',
        NODE_ENV: 'production',
        EXT_APP_ENV: 'production'
      }
    }
  }

  const env = Object.keys(envs).find(key => envs[key].enable)
  process.env = {
    ...process.env,
    ...envs[env]?.env
  }
}

defineEnv(
  process.argv
    .find(item => /mode=/.test(item))
    ?.split('=')
    ?.pop(),
  process.argv
    .find(item => /debug=/.test(item))
    ?.split('=')
    ?.pop()
)

const config = envFileReader(`.env.${process.env.EXT_APP_ENV}`)

const envConfig = Object.keys(config).reduce((accumulator, currentKey) => {
  if (!['NODE_ENV'].includes(currentKey)) {
    try {
      accumulator[currentKey] = JSON.parse(config[currentKey])
    } catch (error) {
      accumulator[currentKey] = config[currentKey].replace(/^["|'](.*)["|']$/, '$1')

      if (/URL/.test(currentKey)) {
        accumulator[currentKey] = accumulator[currentKey].replace(/\/+$/, '')
      }
    }
  }

  return accumulator
}, {})

module.exports = envConfig
